﻿//==============================================================================
//  File Name   :   GalleryAlbumRenderer.cs
//
//  Copyright © 2007 by Do Hong Ngoc. All rights reserved.
//
//  Distributable under GPL code license.
//  See terms of license at www.bbquyen.com.
//
//==============================================================================

// <fileinformation>
//   <summary>
//     This file defines the GalleryAlbumRenderer class.
//   </summary>
//   <author name="Do Hong Ngoc" mail="whiterose1611vn@yahoo.co.uk"/>
//   <date>4/3/2007 2:24:58 PM</date>
//   <remarks>
//     
//   </remarks>
// </fileinformation>

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using BbqFramework.Web.UI.Controls;
using System.IO;
using System.Globalization;
using BbqFramework.Web.UI;

namespace Bbq.Gallery.UI
{
	#region GalleryAlbumRenderer class
	/// <summary>
	/// Defines GalleryAlbumRenderer class.
	/// </summary>
    [ToolboxItem(false)]
    public class GalleryAlbumRenderer : WebUpdatePanel, INamingContainer, ISupportCustomContextMenu
	{
		#region Constants
		private const string CUSTOM_CONTEXT_MENU_ID = "Pic";
		#endregion

		#region Private Fields
		private GalleryAlbum _galleryAlbum = null;
		#endregion

		#region Public Protected Properties
		/// <summary>
		/// Gets or sets a value indicating whether [show tool tip].
		/// </summary>
		/// <value><c>true</c> if [show tool tip]; otherwise, <c>false</c>.</value>
		[Category("Gallery")]
		[DefaultValue(false)]
		public bool ShowToolTip
		{
			get
			{
				object obj = this.ViewState["ShowToolTip"];
				return obj == null ? false : (bool)obj;
			}
			set { this.ViewState["ShowToolTip"] = value; }
		}

		/// <summary>
		/// Gets or sets a value indicating whether this <see cref="GalleryAlbumRenderer"/> is fading.
		/// </summary>
		/// <value><c>true</c> if fading; otherwise, <c>false</c>.</value>
		[Category("Gallery")]
        [DefaultValue(FadingModes.FadingOut)]
		public FadingModes Fading
		{
			get
			{
				object obj = this.ViewState["Fading"];
                return obj == null ? FadingModes.FadingOut : (FadingModes)obj;
			}
			set { this.ViewState["Fading"] = value; }
		}

        /// <summary>
        /// Gets or sets a value indicating whether we implement fading effect when the mouse is out of control.
        /// </summary>
        /// <value><c>true</c> if we use fading effect for all time; otherwise, <c>false</c>.</value>
        public bool FullFading
        {
            get
            {
                object obj = this.ViewState["FullFading"];
                return obj == null ? false : (bool)obj;
            }
            set { this.ViewState["FullFading"] = value; }
        }

        /// <summary>
        /// Gets or sets the opacity which will be use for fading effect.
        /// This value is different the opacity which is defined by browser.
        /// 0% means totaly transparent
        /// 100% means solid.
        /// </summary>
        /// <value>The opacity.</value>
        public int Opacity
        {
            get
            {
                object obj = this.ViewState["Opacity"];
                return obj == null ? 30 : (int)obj; //30 means 70% opacity in browser
            }
            set
            {
                if (value < 0 || value > 100)
                    throw new ArgumentOutOfRangeException("Opacity", "The value must be in 0 to 100");
                this.ViewState["Opacity"] = value;
            }
        }

        internal GalleryAlbum Album
        {
            get { return _galleryAlbum; }
        }
		#endregion

		#region Internal Private Properties
		#endregion

		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="GalleryAlbumRenderer"/> class.
		/// </summary>
		public GalleryAlbumRenderer(GalleryAlbum galleryAlbum)
			: base()
		{
			//Data
			_galleryAlbum = galleryAlbum;

			this.EnableViewState = false;
			this.UpdateMode = UpdatePanelUpdateMode.Conditional;

            //Initialization
            this.Width = Unit.Pixel(167);
            this.Height = Unit.Pixel(150);
            this.Padding = new System.Windows.Forms.Padding(5);
            this.Float = FloatMode.Left;
		}
		#endregion

		#region Override Functions

        ///// <summary>
        ///// Renders the children.
        ///// </summary>
        ///// <param name="writer">The writer.</param>
        //protected override void RenderChildren(HtmlTextWriter writer)
        //{
        //    if (this.IsInPartialRendering)
        //    {
        //        base.RenderChildren(writer);
        //    }
        //    else
        //    {
        //        //Initialization for default gallery item
        //        writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "167px");
        //        writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "150px");
        //        writer.AddStyleAttribute("float", "left");
        //        writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "5px 5px 5px 5px");
        //        base.RenderChildren(writer);
        //    }
        //}

		/// <summary>
		/// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			ClientScriptManager clientScript = this.Page.ClientScript;
			//Register CSS
			object obj = this.Page.Items["BBQGallery_ManagementCssClass.css"];
			if (obj == null)
			{
				this.Page.Items["BBQGallery_ManagementCssClass.css"] = true;
				string urlCSS = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.ManagementCssClass.css");
				Literal cssCtrl = new Literal();
				cssCtrl.Text = @"
<style type=""text/css"">@import url(""" + urlCSS + @""");</style>";
				this.Page.Header.Controls.Add(cssCtrl);
			}
		}

		/// <summary>
		/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
		/// </summary>
		protected override void CreateChildControls()
		{
			//Ensure that each control will be displayed one time
			this.ContentTemplateContainer.Controls.Clear();

			ClientScriptManager clientScript = this.Page.ClientScript;

			HiddenField idAlbum = new HiddenField();
			idAlbum.ID = "idAlbum";
			idAlbum.Value = GalleryHelper.ResolveAlbumIdentity(_galleryAlbum);
			this.ContentTemplateContainer.Controls.Add(idAlbum);

			Literal albumRenderText = new Literal();
			albumRenderText.EnableViewState = false;
			albumRenderText.ID = "albumRenderText";
			albumRenderText.Text = BuildAlbum();
			this.ContentTemplateContainer.Controls.Add(albumRenderText);

			PlaceHolder editArea = new PlaceHolder();
			editArea.ID = "editArea";
			this.ContentTemplateContainer.Controls.Add(editArea);
			LiteralControl divEditArea = new LiteralControl();
			divEditArea.ID = "divEditArea";
			editArea.Controls.Add(divEditArea);
			divEditArea.Text = string.Concat("<div style=\"display: none;\" id=\"", divEditArea.ClientID, "\">");

			TextBox txtAlbumName = new TextBox();
			txtAlbumName.Columns = 16;
			txtAlbumName.ID = "txtAlbumName";
			txtAlbumName.Text = _galleryAlbum.Name;
			editArea.Controls.Add(txtAlbumName);

			Button ibChangeAlbumName = new Button();
			ibChangeAlbumName.Text = "Save";
			ibChangeAlbumName.EnableViewState = false;
			ibChangeAlbumName.ID = "ibChangeItemName";
			ibChangeAlbumName.Click += ibChangeAlbumName_Click;
			ibChangeAlbumName.OnClientClick = "__bbqGallery_RenameAlbum(true,null,null,this);";
			editArea.Controls.Add(ibChangeAlbumName);

			LiteralControl endDiv = new LiteralControl("</div>");
			editArea.Controls.Add(endDiv);

			Panel descControl = new Panel();
			descControl.ID = "descControl";
            descControl.Attributes["unselectable"] = "on";
            descControl.Style["-moz-user-select"] = "none";
            descControl.Attributes["onselectstart"] = "return false;";
            this.ContentTemplateContainer.Controls.Add(descControl);

			LiteralControl albumNameControl = new LiteralControl(_galleryAlbum.Name);
			albumNameControl.ID = "albumNameControl";
			descControl.Controls.Add(albumNameControl);

			//string renameClientScript = string.Concat("__bbqGallery_Show('", divEditArea.ClientID, "');__bbqGallery_Hide('", descControl.ClientID, "'); return false;");
			descControl.Attributes["ondblclick"] = string.Concat("__bbqGallery_RenameAlbum(false, '", divEditArea.ClientID, "','", descControl.ClientID, "');");

            //this.CreateContextMenuItems(renameClientScript);

			//Fake TargetControl for ModalPopupExtender
			//LinkButton lnkModal = new LinkButton();
			//lnkModal.ID = "lnkModal";
			//lnkModal.Style[HtmlTextWriterStyle.Display] = "none";
			//this.ContentTemplateContainer.Controls.Add(lnkModal);
			//this.CreateNewAlbumModalDialog(lnkModal);

			//ContextMenuItem createAlbum = this.ContextMenu.MenuItems[2];	//2 = createAlbum
			//createAlbum.OnClientClick = "__bbqGallery_SimulateClick($get('" + lnkModal.ClientID + "'));return false;";

			//this.ContentTemplateContainer.Controls.Add(this.ContextMenu);
		}

		#endregion

		#region Private Functions

		/// <summary>
		/// Handles the Click event of the ibChangeAlbumName control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		void ibChangeAlbumName_Click(object sender, EventArgs e)
		{
			GalleryProvider provider = Gallery.GalleryProvider;
			string newName = (this.FindControl("txtAlbumName") as TextBox).Text;
			HiddenField idAlbum = (this.FindControl("idAlbum") as HiddenField);
			string id = idAlbum.Value;

			_galleryAlbum = provider.GetGalleryAlbumInfo(provider.GetActualAlbumIdentity(id));
			GalleryAlbum oldAlbum = (GalleryAlbum)_galleryAlbum.Clone();
			_galleryAlbum.Name = newName;
			provider.UpdateGalleryAlbum(oldAlbum, _galleryAlbum);
			LiteralControl albumNameControl = this.FindControl("albumNameControl") as LiteralControl;
			albumNameControl.Text = newName;
			idAlbum.Value = provider.ResolveAlbumIdentity (_galleryAlbum);

			Literal albumRenderText = this.FindControl("albumRenderText") as Literal;
			albumRenderText.Text = BuildAlbum();
		}

		/// <summary>
		/// Builds the album.
		/// </summary>
		/// <returns></returns>
		private string BuildAlbum()
		{
			ClientScriptManager clientScript = this.Page.ClientScript;
			StringBuilder sb = new StringBuilder();

			string urlLeft = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.left.gif");
			string urlTop = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.top.gif");
			string urlRight = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.right.gif");
			string urlBottom = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.bottom.gif");

			sb.Append(@"<table border=""0"" cellpadding=""0"" cellspacing=""0"" width=""100%"" id=""");
			sb.Append(this.ClientID + CUSTOM_CONTEXT_MENU_ID);
			sb.Append(@""">
<tr>
<td colspan=""3""><img border=""0"" alt="""" src=""");
			sb.Append(urlTop);
			sb.Append(@""" /></td>
</tr>
<tr>
<td><img border=""0"" alt="""" src=""");
			sb.Append(urlLeft);
			sb.Append(@""" /></td>
<td><a href=""");
			//link to album
			sb.Append(Gallery.GalleryProvider.ResolveAlbumLink(_galleryAlbum));
			sb.Append(@"""><img");
            //Fading
            //int browserOpacity = 100 - this.Opacity;
            string fullFading = this.FullFading ? "true" : "false";
			switch (this.Fading)
			{
				case FadingModes.Opacity:
                    sb.Append(@" onmouseover=""__bbqGallery_AlbumHover(this, 100, 100, false, true, false)"" onmouseout=""__bbqGallery_AlbumHover(this, ");
                    sb.Append(this.Opacity);
                    sb.Append(", ");
                    sb.Append(this.Opacity);
                    sb.Append(@", false, false, false)""");
					break;
				case FadingModes.FadingIn:
                case FadingModes.FadingOut:
                    if (this.Fading == FadingModes.FadingOut)
                    {
                        sb.Append(@" style=""filter:alpha(opacity=");
                        sb.Append(this.Opacity);
                        sb.Append(@");-moz-opacity:");
                        sb.Append((((float)this.Opacity) / 100).ToString("#.##"));
                        sb.Append(@";""");
                    }
                    sb.Append(@" onmouseover=""__bbqGallery_AlbumHover(this, ");
                    sb.Append(this.Fading == FadingModes.FadingOut ? this.Opacity : 100);
                    sb.Append(",");
                    sb.Append(this.Fading == FadingModes.FadingOut ? 100 : this.Opacity);
                    sb.Append(",");
                    sb.Append(fullFading);
                    sb.Append(@",true, false)"" onmouseout=""__bbqGallery_AlbumHover(this,");
                    sb.Append(this.Fading == FadingModes.FadingOut ? 100 : this.Opacity);
                    sb.Append(",");
                    sb.Append(this.Fading == FadingModes.FadingOut ? this.Opacity : 100);
                    sb.Append(",");
                    sb.Append(fullFading);
                    sb.Append(@",false, false)""");
                    break;
                case FadingModes.CircleIn:
                    break;
                case FadingModes.CircleOut:
                    break;
                //default:    //FadingModes.None
			}
			sb.Append(@" border=""0"" al="""" width=""135"" height=""101"" src=""");
			//img link
			GetThumbnailUrl(sb);
			sb.Append("\"");
			if (this.ShowToolTip)
			{
				BoxOver box = new BoxOver();
				box.ControlToValidate = this.ID;
				this.Controls.Add(box);
				box.Header = _galleryAlbum.Name;
				box.Body = string.Concat(_galleryAlbum.Description, "<br />Created: ", _galleryAlbum.CreatedDate.ToString("dd/MM/yyyy"), "<br />Last Modified: ", _galleryAlbum.LastModifiedDate.ToString("dd/MM/yyyy"));
			}
			sb.Append(@" /></a></td>
<td><img border=""0"" alt="""" src=""");
			sb.Append(urlRight);
			sb.Append(@""" /></td>
</tr>
<tr>
<td colspan=""3""><img border=""0"" alt="""" src=""");
			sb.Append(urlBottom);
			sb.Append(@""" /></td>
</tr>
</table>");

			return sb.ToString();
		}

		/// <summary>
		/// Gets the thumbnail URL.
		/// </summary>
		/// <returns></returns>
		private void GetThumbnailUrl(StringBuilder sb)
		{
			sb.Append("BbqThumbnailHandler.ashx?");
			sb.Append(GalleryHelper.THUMBNAIL_MODE);
			sb.Append('=');
			sb.Append(GalleryHelper.ThumbnailModes.Album);
			//sb.Append('&');
			//sb.Append(GalleryHelper.THUMBNAIL_IMAGETYPE);
			//sb.Append('=');
			//sb.Append(BbqFramework.Drawing.CodecInfos.JPEG.CodecName);
			sb.Append('&');
			sb.Append(Gallery.GALLERY_ALBUM_ID);
			sb.Append('=');
			sb.Append(Gallery.GalleryProvider.ResolveAlbumIdentity(_galleryAlbum));
		}
		#endregion

		#region Events
		#endregion


		#region ISupportCustomContextMenu Members

		/// <summary>
		/// Gets the target client id.
		/// </summary>
		/// <value>The target client id.</value>
		string ISupportCustomContextMenu.TargetClientId
		{
			get { return this.ClientID + CUSTOM_CONTEXT_MENU_ID; }
		}

		#endregion
	}
	#endregion
}
